import {reqCartList,reqDeleteCartById,reqUpdateCheckedById} from '@/api'
const state = {
    cartList:[]
};
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList=cartList
    }
};
const actions = {
 //获取购物车列表的数据
   async getCartList({commit}) {
        let result = await reqCartList()
        if (result.code == 200) {
            commit('GETCARTLIST',result.data)
        }
        // console.log(result);
    },
    
  //删除购物车产品
    async deleteCartListById({ commit }, skuId) {
       let result = await reqDeleteCartById(skuId);
       if (result.code == 200) {
           return 'ok'
       } else {
           Promise.reject(new Error('faile'))
       }
    },
 //修改购物车某一个产品的选中状态
   async reqUpdateCheckedById({ commit }, { skuId, isChecked }) {
       let result = await reqUpdateCheckedById(skuId, isChecked);
       if (result.code == 200) {
           return 'ok';
       } else {
           Promise.reject(new Error('faile'))
       }
    },
   //删除勾选的产品
    deleteChecked({dispatch,getters}) {
       //context:仓库  commit getters dispath state
        //获取购物车中全部的产品
        let promiseAll = [];
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCartListById', item.skuId) : '';
            promiseAll.push(promise)
        });
        //只要promise全部成功 返回值为成功
        //有一个失败  返回值为失败
        return Promise.all(promiseAll);
    },
    //修改全选状态
    allChecked({ dispatch, state }, isChecked) {
        let promiseAll = [];
        state.cartList[0].cartInfoList.forEach(item => {
            let promise = dispatch('reqUpdateCheckedById', { skuId: item.skuId, isChecked });
            promiseAll.push(promise);
        });
        return Promise.all(promiseAll)
    }
};

const getters = {
    //简化cartList
    cartList(state) {
        return state.cartList[0]||{}
    }
};
export default {
    state,
    mutations,
    actions,
    getters
}
